/**
 * Copyright (c) 2006-2008, Julien PORTALIER
 * 
 * Licensed under The LGPL License
 * Redistributions of files must retain the above copyright notice.
 * 
 * @copyright  Copyright (c) 2006-2008, Julien PORTALIER
 * @link       http://feather-cm.googlecode.com/
 * @license    http://www.opensource.org/licenses/lgpl-license.php The LGPL License
 */

if (!Textarea)
	var Textarea = {};

/**
 * Automatically resizes a textarea depending on it's content.
 * 
 * @param {Textarea Element} textarea
 * @param {Object} options
 */
Textarea.AutoResize = new Class(
{
	initialize: function(textarea, options)
	{
		this.textarea = $(textarea);
		this.textarea.setStyles({
			'overflow-x': 'auto',
			'overflow-y': 'hidden'
		});
		
		this.options = {
			'delay':  100,
			'minHeight': this.textarea.offsetHeight
		};
		this.setOptions(options);
		
		// we use an hidden textarea to calculate new height
		this.fake = this.textarea.clone();
		
		this.fake.removeAttribute('tabindex');
		this.fake.removeAttribute('name');
		this.fake.removeAttribute('id');
		
		// fix for mootools 1.11 & 1.2b2
		var size = this.textarea.getSize();
		if (size.size)
			size = size.size;
		
		this.fake.addClass('fake').setStyles({
			'visibility': 'hidden',
			'position': 'absolute',
			'z-index': -1,
			'top':   this.textarea.offsetTop  + 'px',
			'left':  this.textarea.offsetLeft + 'px',
			'width': size.x + 'px',
			'margin': 0
		});
		this.fake.injectAfter(this.textarea);
		
		// apply new height
		this.run();
		
		// events
		this.textarea.addEvent('keypress', this.delay.bind(this));
	},
	
	delay: function(evt)
	{
		$clear(this.delay);
		this.delay = this.run.delay(this.options.delay, this);
	},
	
	run: function()
	{
		// update fake's content
		this.fake.value = this.textarea.value;
		
		// calculate new height (using fake)
		this.fake.setStyle('height', this.options.minHeight + 'px');
		this.fake.setStyle('height', this.fake.scrollHeight + 20 + 'px');
		var newHeight = Math.max(this.fake.offsetHeight, this.options.minHeight);
		
		// limiting height to 70% window height
		var maxHeight = window.getHeight() * 0.7;
		if (newHeight > maxHeight)
		{
			this.textarea.setStyles({'overflow-y': 'auto'});
			newHeight = maxHeight;
		}
		else {
			this.textarea.setStyles({'overflow-y': 'hidden'});
		}
		
		// set new height (if it changed)
		if (this.textarea.offsetHeight != newHeight) 
			this.textarea.setStyle('height', newHeight + 'px');
	}
});
Textarea.AutoResize.implement(new Options());

window.addEvent('load', function()
{
	$$('form textarea.resize').each(function(textarea)
	{
//		if (!textarea.hasClass('noresize'))
//		{
			new Textarea.AutoResize(textarea);
//		}
	});
});